import { selector, atom, selectorFamily } from "recoil";
import { getStuListApi, getStuByIdApi } from "../api/stuApi";

// 用户搜索输入的内容
const search = atom({
  key: "search",
  default: "",
});

// 创建一个 requestID
const requestId = atom({
  key: "requestId",
  default: 0,
});

// 获取学生列表
// 注意这里涉及到异步请求，在 recoil 里面，异步请求仍然是使用 selector 来处理
// 也就说，在 recoil 中，同步和异步都是通过 selector 同一套接口来处理的
const stuListStateSelector = selector({
  key: "stuListStateSelector",
  get: async ({ get }) => {
    get(requestId);
    const stuList = await getStuListApi();
    // 依赖 requestID
    // 获取搜索内容的值
    const searchContent = get(search);
    // 接下来根据用户搜索的值来进行过滤
    if (searchContent) {
      return stuList.filter((item) => {
        return item.stuname.includes(searchContent);
      });
    } else {
      return stuList;
    }
  },
});

// 根据 id 获取学生详情
const stuInfoSelector = selectorFamily({
  key: "stuInfoSelector",
  get: (id) => async ({get}) => {
    get(requestId);
    return await getStuByIdApi(id as string);
  },
});

// alert 的提示信息
const alertInfo = atom({
  key: "alertInfo",
  default: {
    type: "default",
    message: "",
  },
});

// 表单数据
const formState = atom({
  key: "formState",
  default: {
    stuname: "",
    stuage: 0,
    phone: "",
    email: "",
    education: "本科",
    graduationschool: "",
    profession: "",
    profile: "",
  },
});

export {
  stuListStateSelector,
  search,
  stuInfoSelector,
  requestId,
  alertInfo,
  formState,
};
